package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.common.model.Book;
import org.example.request.BookRequest;
import org.example.service.BookService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.xml.bind.ValidationException;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/books")
public class BookController {
    private final BookService bookService;

    @PostMapping("/add")
    public ResponseEntity<Long> createBook(@Validated @RequestBody BookRequest request) throws ValidationException {
        return ResponseEntity.ok(bookService.createBook(request));
    }
    @GetMapping("/get/{id}")
    public ResponseEntity<Book> getBook(@PathVariable("id") Long id) {
        return ResponseEntity.ok(bookService.getBookById(id));
    }
    @PostMapping("/update/{id}")
    public ResponseEntity<Void> updateBook(@PathVariable Long id, @Validated @RequestBody BookRequest request) throws ValidationException {
        Book book = bookService.getBookById(id);
        if (book == null){
            return ResponseEntity.notFound().build();
        }
        bookService.updateBook(id, request);
        return ResponseEntity.noContent().build();
    }
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Void> deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return ResponseEntity.noContent().build();
    }
}